package com.easygoods.shiro.auth;

import com.bestvike.stone.core.lang.RandomUtils;
import com.bestvike.stone.core.time.DateUtils;
import com.bestvike.stone.spring.shiro.auth.Auth;
import com.easygoods.entity.MemberInfo;
import com.easygoods.enums.Channel;
import com.easygoods.enums.LoginUserType;
import com.easygoods.response.LoginResponse;
import com.easygoods.service.AuthService;
import lombok.Data;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by 许崇雷 on 2019-03-13.
 */
@Data
public final class UserAuth implements Auth {
    //token
    private String token;
    //登录渠道外部(可能为 null)
    private Channel channel;
    private String openId;
    //登录时间
    private Date loginTime;
    //用户信息
    private String memberId;
    private String nickName;
    private String mobile;
    private String email;
    private String refMemberId;
    private Date registerTime;
    //权限
    private Set<String> roles;
    private Set<String> permissions;
    //登录类型
    private LoginUserType loginUserType;

    //登录失败
    public static UserAuth loginFail(LoginUserType loginUserType) {
        final UserAuth userAuth = new UserAuth();
        userAuth.loginUserType = loginUserType;
        return userAuth;
    }

    //登录成功
    public static UserAuth loginSuccess(Channel channel, String openId, MemberInfo memberInfo, LoginUserType loginUserType) {
        final UserAuth userAuth = new UserAuth();
        userAuth.token = RandomUtils.randomUUID();
        userAuth.channel = channel;
        userAuth.openId = openId;
        userAuth.loginTime = DateUtils.now();
        userAuth.memberId = memberInfo.getId();
        userAuth.nickName = memberInfo.getNickName();
        userAuth.mobile = memberInfo.getMobile();
        userAuth.email = memberInfo.getEmail();
        userAuth.refMemberId = memberInfo.getRefMemberId();
        userAuth.registerTime = memberInfo.getRegisterTime();
        userAuth.roles = new HashSet<>(1);
        userAuth.roles.add(UserRoles.USER);
        userAuth.permissions = new HashSet<>(1);
        userAuth.permissions.add(UserPermissions.BUY);
        userAuth.loginUserType = loginUserType;
        return userAuth;
    }

    //是否有效
    @Override
    public boolean isAuthenticated() {
        return this.channel == null || AuthService.hasOpenId(this.channel, this.openId);
    }

    //转换为登陆响应
    public LoginResponse toResponse() {
        return new LoginResponse(this.token, this.memberId, this.loginUserType);
    }
}
